﻿using System.Text;
using System.Text.Json;
using GrapeCity.Forguncy.ServerApi;

namespace MyApiTest;

public class RequestBodyHandler : ForguncyApi
{
    [Post]
    public async Task ReceiveApiRequest()
    {
        var request = Context.Request;
        var serverCommandName = request.Query["serverCommandName"];
        if (request.ContentType != null && request.ContentType.Equals("application/json"))
        {
            var sr = new StreamReader(request.Body);
            string content = await sr.ReadToEndAsync();

            var obj = new { data = content };
            string newContent = JsonSerializer.Serialize(obj).Replace("/r/n", "");

            using HttpClient httpClient = new HttpClient();
            var baseAddress = $"{request.Scheme}://{request.Host}{request.PathBase}/ServerCommand/{serverCommandName}";
            HttpContent httpContent = new StringContent(newContent, Encoding.UTF8, "application/json");
            HttpResponseMessage responseMessage = await httpClient.PostAsync(baseAddress, httpContent);

            if (responseMessage.IsSuccessStatusCode)
            {
                await responseMessage.Content.ReadAsStringAsync();
            }
            else
            {
                throw new Exception($"Error: {responseMessage.StatusCode}");
            }
        }
        else
        {
            throw new HttpRequestException("ContentType error, please check request content!");
        }
    }
}